<template>
	<main-container>
		<!-- 搜索 -->
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
			<el-form-item label="商品名称">
				<el-input v-model="queryParams.name" clearable></el-input>
			</el-form-item>
			<el-form-item label="商品类目">
				<el-cascader :options="goodsCategoryList" v-model="queryParams.categorySecondId" clearable :props="defaultProps"></el-cascader>
			</el-form-item>
			<el-form-item label="商品规格">
				<el-select v-model="state.queryParams.enableSpecs" clearable>
					<el-option v-for="item in goods_specs" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="商品状态">
				<el-select v-model="state.queryParams.status" clearable>
					<el-option v-for="item in goods_status" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="initPage"
					><el-icon> <ele-Search /> </el-icon>搜索</el-button
				>
				<el-button @click="restQuery"
					><el-icon> <ele-Refresh /> </el-icon>重置</el-button
				>
			</el-form-item>
		</el-form>
		<!-- 工具栏 -->
		<div class="hx-table-toolbar mb10">
			<div>
				<el-button type="primary" v-auth="'product:goodsspu:add'" @click="add"
					><el-icon> <ele-Plus /> </el-icon>新增</el-button
				>
				<el-button type="success" v-auth="'product:goodsspu:edit'" @click="goodsShelf('1')" :disabled="multipleSelection.length <= 0"
					>批量上架</el-button
				>
				<el-button type="danger" v-auth="'product:goodsspu:edit'" @click="goodsShelf('0')" :disabled="multipleSelection.length <= 0"
					>批量下架</el-button
				>
				<el-button type="warning" v-auth="'product:goodsspu:verify'" @click="handleVerify" :disabled="multipleSelection.length <= 0"
					>批量审核</el-button
				>
			</div>
			<right-toolbar :searchBtn="true" :refreshBtn="true" @search="showSearch = !showSearch" @refresh="initPage"></right-toolbar>
		</div>
		<el-tabs v-model="state.active" type="card" @tab-click="handleActive">
			<el-tab-pane label="全部" name=""></el-tab-pane>
			<el-tab-pane label="审核中" name="0"></el-tab-pane>
			<el-tab-pane label="审核通过" name="1"></el-tab-pane>
			<el-tab-pane label="审核驳回" name="2"></el-tab-pane>
		</el-tabs>
		<!-- 列表 -->
		<el-table v-loading="loading" :data="tableData" border @selection-change="handleSelectionChange" style="width: 100%">
			<el-table-column type="selection" width="50" align="center" />
			<el-table-column prop="spu" label="商品信息" width="300">
				<template #default="scope">
					<el-row>
						<el-col :span="6">
							<el-image
								style="width: 60px; height: 60px"
								:src="scope.row.spuUrls[0]"
								:preview-src-list="scope.row.spuUrls"
								fit="cover"
								:preview-teleported="true"
							></el-image>
						</el-col>
						<el-col :span="18" style="float: left">
							<span class="overflow-line-clamp-2">{{ scope.row.name }}</span>
							<div class="overflow-line-clamp-1" style="font-size: 13px; color: #909399">{{ scope.row.subTitle }}</div>
						</el-col>
					</el-row>
				</template>
			</el-table-column>
			<el-table-column prop="categoryName" label="商品类目" align="center" width="100" />
			<el-table-column prop="salesPrice" label="价格（元）" align="center" width="160">
				<template #default="scope">
					<span v-if="scope.row.lowPrice == scope.row.highPrice" style="color: red">￥{{ scope.row.lowPrice }}</span>
					<span v-else style="color: red">￥{{ scope.row.lowPrice }} - ￥{{ scope.row.highPrice }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="status" label="商品状态" align="center" width="100">
				<template #default="scope">
					<dict-tag :options="goods_status" :value="scope.row.status"></dict-tag>
				</template>
			</el-table-column>
			<el-table-column prop="enableSpecs" label="规格" align="center" width="100">
				<template #default="scope">
					<dict-tag :options="goods_specs" :value="scope.row.enableSpecs"></dict-tag>
				</template>
			</el-table-column>
			<el-table-column prop="salesVolume" label="销量" align="center" width="100" />
			<el-table-column prop="verifyStatus" label="审核状态" align="center">
				<template #default="scope">
					<dict-tag :options="goods_verify_status" :value="scope.row.verifyStatus"></dict-tag>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" align="center" width="160" />
			<el-table-column label="操作" width="150" align="center" fixed="right">
				<template #default="scope">
					<el-button link type="primary" v-auth="'product:goodsspu:edit'" @click="edit(scope.row)"
						><el-icon> <ele-Edit /> </el-icon>修改</el-button
					>
					<el-button link type="danger" v-auth="'product:goodsspu:del'" @click="del(scope.row.id)"
						><el-icon> <ele-Delete /> </el-icon>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页 -->
		<pagination
			v-model:total="page.total"
			v-model:currentPage="page.currentPage"
			v-model:pageSize="page.pageSize"
			@changePage="initPage"
		></pagination>
		<el-dialog v-model="verifyDialog.open" title="商品审核" width="60%">
			<el-form ref="verifyDialogForm" :model="verifyDialog.form">
				<el-form-item label="商品信息">
					<el-table :data="multipleSelection" style="width: 100%" max-height="500" border>
						<el-table-column prop="shopName" label="店铺" align="center" width="200" />
						<el-table-column prop="spu" label="商品信息">
							<template #default="scope">
								<el-row>
									<el-col :span="6">
										<el-image
											style="width: 60px; height: 60px"
											:src="scope.row.spuUrls[0]"
											:preview-src-list="scope.row.spuUrls"
											fit="cover"
											:preview-teleported="true"
										></el-image>
									</el-col>
									<el-col :span="18" style="float: left">
										<span class="overflow-line-clamp-2">{{ scope.row.name }}</span>
										<div class="overflow-line-clamp-1" style="font-size: 13px; color: #909399">{{ scope.row.subTitle }}</div>
									</el-col>
								</el-row>
							</template>
						</el-table-column>
						<el-table-column prop="categoryName" label="商品类目" align="center" width="100" />
						<el-table-column prop="salesPrice" label="价格（元）" align="center" width="160">
							<template #default="scope">
								<span v-if="scope.row.lowPrice == scope.row.highPrice" style="color: red">￥{{ scope.row.lowPrice }}</span>
								<span v-else style="color: red">￥{{ scope.row.lowPrice }} - ￥{{ scope.row.highPrice }}</span>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
				<el-form-item label="审核描述">
					<el-input v-model="verifyDialog.form.verifyDesc" type="textarea" />
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="submitVerifyForm('2')" :disabled="loading">审核驳回</el-button>
					<el-button type="primary" @click="submitVerifyForm('1')" :disabled="loading"> 审核通过 </el-button>
				</div>
			</template>
		</el-dialog>
	</main-container>
</template>
<script lang="ts" setup>
import { ref, reactive, toRefs } from 'vue';
import { getPage, delObj, goodsShelf as goodsShelfOpt, verify } from '/@/api/product/goodsspu';
import { getPage as getCategoryTree } from '/@/api/product/goodscategory';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useDict } from '/@/utils/dict';

const { goods_verify_status, goods_status, goods_specs } = useDict('goods_verify_status', 'goods_status', 'goods_specs');
const state = reactive({
	queryParams: {
		name: '',
		status: '',
		enableSpecs: '',
		categorySecondId: '',
	},
	page: {
		total: 0,
		currentPage: 1,
		pageSize: 10,
		descs: 'create_time',
	},
	tableData: [],
	active: '',
});
// 商品类目
const goodsCategoryList = ref([]);
const defaultProps = {
	label: 'name',
	value: 'id',
	children: 'children',
	emitPath: false,
};
// 审核弹窗
const verifyDialog = ref({
	open: false,
	form: {
		verifyStatus: '2',
		verifyDesc: '',
		spuIds: [],
	},
	goodsList: [],
});
const multipleSelection = ref<any>([]);
const showSearch = ref(true);
const $route = useRouter();
const loading = ref(false);
const { tableData, queryParams, page } = toRefs(state);
/**
 * 查询全部商品类目
 */
const getCategory = () => {
	getCategoryTree().then((response) => {
		goodsCategoryList.value = response.data.data;
	});
};
const initPage = async () => {
	loading.value = true;
	let params = {
		current: page.value.currentPage,
		size: page.value.pageSize,
		descs: page.value.descs,
		verifyStatus: state.active,
	};
	await getPage(Object.assign(params, queryParams.value))
		.then((response) => {
			tableData.value = response.data.data.records;
			page.value.total = response.data.data.total;
			loading.value = false;
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 重置搜索表单
 */
const restQuery = () => {
	queryParams.value = { name: '', status: '',  enableSpecs: '', categorySecondId: '' };
};
/**
 * 新增按钮
 */
const add = () => {
	$route.push({ path: '/product/goods/spu/form' });
};
/**
 * 修改按钮
 */
const edit = (row: any) => {
	$route.push({ path: '/product/goods/spu/form', query: { id: row.id } });
};
/**
 * 删除按钮
 */
const del = (id: string) => {
	ElMessageBox.confirm('此操作将删除该商品，是否继续?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		delObj(id)
			.then((response) => {
				ElMessage.success('删除成功');

				initPage();
			})
			.catch(() => {});
	});
};
/**
 * 商品上下架
 */
const goodsShelf = (status: string) => {
	if (!multipleSelection.value || multipleSelection.value.length <= 0) {
		return ElMessage.warning('请选择商品');
	}
	loading.value = true;
	const ids = multipleSelection.value.map((item: any) => item.id);
	goodsShelfOpt({ status: status, spuIds: ids })
		.then((response) => {
			ElMessage.success('操作成功');
			loading.value = false;
			initPage();
		})
		.catch(() => {
			loading.value = false;
		});
};
/**
 * 当选择项发生变化时会触发该事件
 */
const handleSelectionChange = (val: any) => {
	multipleSelection.value = val;
};
/**
 * 批量审核
 */
const handleVerify = () => {
	verifyDialog.value.open = true;
	verifyDialog.value.form.spuIds = [];
	verifyDialog.value.form.verifyDesc = '';
};
const submitVerifyForm = (status: string) => {
	if (!multipleSelection.value || multipleSelection.value.length <= 0) {
		return ElMessage.warning('请选择商品');
	}
	loading.value = true;
	const ids = multipleSelection.value.map((item: any) => item.id);
	verify({ verifyStatus: status, spuIds: ids, verifyDesc: verifyDialog.value.form.verifyDesc })
		.then(() => {
			ElMessage.success('审核成功');
			loading.value = false;
			verifyDialog.value.open = false;
			initPage();
		})
		.catch(() => {
			loading.value = false;
		});
};
const handleActive = (event: any) => {
	state.active = event.paneName;
	initPage();
};
getCategory();
initPage();
</script>
